# from app.order.purchase.model import PurchaseOrder as PurchaseOrderTable
# from app.order.purchase.model import PurchaseOrderSku as PurchaseOrderSkuTable
# from common.mixins import DictMixin
# from exts import db
# import datetime
# from common.constant import OrderStatus, OrderType
# from app.storage.abs_model import Warehouse, WarehouseRecord
# from app.finance.abs_model import Account
# from common import errors
#
#
# class PurchaseOrder:
#     OrderTableClass = PurchaseOrderTable
#     OrderSkuTableClass = PurchaseOrderSkuTable
#     order_sn_prefix = 'CG'
#     order_type = OrderType.PURCHASE
#
#     def __init__(self, order_id=None, user_id=None):
#         self.id = order_id
#         self.user_id = user_id
#         if order_id:
#             self.order_table = self._get_order_table()
#
#     def create_order(self, user_id, order_skus_json, **kwargs):
#         self._create_order_table(user_id, **kwargs)
#         self._create_order_skus(order_skus_json)
#         db.session.commit()
#         return self.order_table
#
#     def save_draft(self, order_skus_json, **kwargs):
#         # 检查状态
#         if self.order_table.status != OrderStatus.DRAFT:
#             raise errors.BadRequestError('无法保存草稿，这不是一个草稿单！')
#         # 更新order
#         new_order_table = DictMixin.from_dict(self.order_table, kwargs)
#         new_order_table.creator_id = self.user_id
#         # 更新order_sku, 先删后增
#         self._delete_order_skus()
#         self._create_order_skus(order_skus_json)
#         db.session.commit()
#         self.order_table = new_order_table
#
#     def submit(self):
#         """入库，入账"""
#         self._get_order_skus_table()
#         # 检查状态
#         if self.order_table.status != OrderStatus.DRAFT:
#             raise errors.BadRequestError('无法提交，这不是一个草稿单！')
#
#         # 修改order状态
#         self.order_table.status = OrderStatus.SUCCESS
#         self.order_table.updater_id = self.user_id
#
#         for order_sku_table in self.order_skus_table:
#             # 更新库存
#             self._update_warehouse_record_by_submit(order_sku_table)
#             # 创建库存流水
#             self._create_warehouse_flow(order_sku_table)
#
#         # 记录财务流水
#         self._create_account_flow()
#
#         db.session.commit()
#
#     def revoke(self):
#         """回退入库，回退财务"""
#         self._get_order_skus_table()
#         # 检查状态
#         if self.order_table.status != OrderStatus.SUCCESS:
#             raise errors.BadRequestError('无法撤销，只有已完成单据可撤销！')
#
#         # 修改order状态
#         self.order_table.status = OrderStatus.REVOKE
#         self.order_table.updater_id = self.user_id
#
#         # 更新库存
#         for order_sku_table in self.order_skus_table:
#             self._update_warehouse_record_by_revoke(order_sku_table)
#
#         # 删除库存流水
#         self._remove_warehouse_flows()
#
#         # 删除财务流水
#         self._revoke_account_flows()
#
#     def _get_order_table(self):
#         return self.OrderTableClass.query.filter_by(id=self.id).first()
#
#     def _get_order_skus_table(self):
#         self.order_skus_table = self.OrderSkuTableClass.query.filter_by(order_id=self.id).all()
#
#     @classmethod
#     def _generate_order_sn(cls):
#         """"""
#         prefix = cls.order_sn_prefix
#         today = datetime.date.today()
#         latest_order = cls.OrderTableClass.query.filter_by().order_by(
#             cls.OrderTableClass.create_datetime.desc()).first()
#         if latest_order:
#             # 找到则加1
#             last_order_sn = latest_order.order_sn
#             prefix, date_str, number = last_order_sn.split('-')
#             current_number = int(number) + 1
#         else:
#             # 未找到设为1
#             current_number = 1
#         return '{}-{}-{}'.format(prefix, today.strftime('%Y%m%d'), generate_sn_str(current_number))
#
#     def _create_order_skus(self, order_skus_json):
#         """创建order sku"""
#         for order_sku_json in order_skus_json:
#             sku_table = DictMixin.from_dict(self.OrderSkuTableClass, order_sku_json)
#             sku_table.creator_id = self.user_id
#             sku_table.order_id = self.order_table.order_id
#             db.session.add(sku_table)
#
#     def _create_order_table(self, user_id, **kwargs):
#         """创建order"""
#         order_table = DictMixin.from_dict(self.OrderTableClass, kwargs)
#         order_table.creator_id = user_id
#         order_table.order_sn = self._generate_order_sn()
#         db.session.add(order_table)
#         db.session.commit()
#         self.order_table = order_table
#
#     def _delete_order_skus(self):
#         order_skus_table_delete = self.OrderSkuTableClass.query.filter_by(order_id=self.id)
#         db.session.delete(order_skus_table_delete)
#
#     def _calculate_should_payment(self):
#         should_payment = 0
#         for order_sku_table in self.order_skus_table:
#             should_payment += order_sku_table.total_price
#         return should_payment
#
#     def _update_warehouse_record_by_submit(self, order_sku_table):
#         """采购 增加数量, 修改成本单价"""
#         warehouse_record = WarehouseRecord(order_sku_table.sku_id, self.order_table.warehouse_id)
#         warehouse_record.add_num(num=order_sku_table.num)
#         warehouse_record.update_cost_price(order_sku_table.num, order_sku_table.real_price)
#
#     def _update_warehouse_record_by_revoke(self, order_sku_table):
#         """采购撤销 减少数量, 修改成本单价"""
#         warehouse_record = WarehouseRecord(order_sku_table.sku_id, self.order_table.warehouse_id)
#         warehouse_record.add_num(num=-order_sku_table.num)
#         warehouse_record.update_cost_price(-order_sku_table.num, order_sku_table.real_price)
#
#     def _create_warehouse_flow(self, order_sku_table):
#         """采购 增加数量"""
#         warehouse = Warehouse(self.order_table.warehouse_id, self.user_id)
#         warehouse.create_flow(self.user_id, self.order_type, self.id, order_sku_table.sku_id, order_sku_table.num)
#
#     def _remove_warehouse_flows(self):
#         """"""
#         warehouse = Warehouse(self.order_table.warehouse_id)
#         warehouse.remove_flow(self.id)
#
#     def _create_account_flow(self):
#         """采购 应付实付"""
#         should_payment = self._calculate_should_payment()
#         account = Account(self.order_table.account_id, self.user_id)
#         account.create_flow_by_order(
#             self.order_type, self.id,
#             should_payment=should_payment,
#             payment=self.order_table.payment)
#
#     def _revoke_account_flows(self):
#         account = Account(self.order_table.account_id, self.user_id)
#         account.remove_flow_by_order(self.id)
#
#
# def generate_sn_str(number_in):
#     template = 1000000
#     return str(number_in + template)[1:]
